package com.kt.common.clazz.entrust

import kotlin.reflect.KProperty

fun main() {

    /*println(Example().p)
    println(Example().i)
    Example().p = "setVal"
    println(Example().p)*/
    //两次调用会执行一次打印computed ，证明by lazy 延迟属性只会初始化一次
    println(lazyValStr)
    println(lazyValStr)
}


class Example {
    //委托属性
    // val/var <属性名>: <类型> by <表达式>
    var p: String by D()
    val i: Int by I()
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return "$thisRef, thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
    }
}

class D {
    operator fun getValue(example: Any?, property: KProperty<*>): String {
        return "$example thank you for delegating '${property.name}' to me!"
    }

    operator fun setValue(example: Any?, property: KProperty<*>, s: String) {
        println("$property has been assigned to '${property.name}' in $example.s=$s")
    }

}

class I {
    operator fun getValue(example: Any, kProperty: KProperty<*>): Int {
        return 2
    }

}


//延迟属性 val + 属性名： 类型 by lazy
val lazyValStr: String by lazy {
    println("computed!")
    "Hello"
}

val lazyValue: String by lazy {
    println("computed!")
    "Hello"
}


//可观察属性 Observable
//Delegates.observable() 接受两个参数：初始值与修改时处理程序（handler）。
// 每当我们给属性赋值时会调用该处理程序（在赋值后执行）。它有三个参数：被赋值的属性、旧值与新值：
